var express = require('express');
var router = express.Router();
var User = require('./user');
var PW = require('png-word');
var pw = new PW();
var R = require('random-word');

/* GET users listing. */
// router.get('/', function(req, res, next) {
//     res.locals.user = req.session.user;
//     console.log(res.locals.user);
//     res.send("index");
// });

//退出
router.get('/logout', function(req, res){
    req.session.user = undefined;
    return res.redirect("/");
})

//登录
router.post('/login', async function(req, res){
    const {loginname, password, vimg} = req.body;

    if(vimg == ""|| vimg == undefined){
        req.session.message ={error:"请输入验证码！"};
    }
    else{
        if(req.session.vimg === vimg) {
            const user = await User.findOne({'loginname':loginname});
            if(user)
            {
                if(user.password === password)
                {
                    req.session.user = {loginname: loginname};
                    req.session.message = undefined;
                }
                else
                {
                    req.session.message ={error:"密码错误，请重新输入！"};
                }
            }
            else{
                req.session.message = {error:"用户不存在！"};
            }
        }
        else{
            req.session.message ={error:"验证码错误，请重新输入！"};
        }
    }
    return res.redirect("/");
})

//注册
router.post('/reg', async function(req, res){
    const {loginname , password , confirm, vimg} = req.body;

    if(vimg == "" || vimg == undefined)
    {
        req.session.message = {error: "请输入验证码！"};
    }
    else
    {
        if(req.session.vimg === vimg) {
            let user = await User.findOne({'loginname':loginname});
            if(user)
            {
                let message = "用户名已存在"
                req.session.message = {error: message};
            }
            else
            {
                //注册成功
                const newUser = new User({
                    loginname,
                    password,
                    confirm
                })
                await newUser.save();
                req.session.message = undefined;
            }
        }
        else{
            req.session.message = {error: "验证码错误，请重新输入！"};
        }
    }
     return res.redirect("/");
})

router.get('/vimg', function(req, res){
    var r = new R("1234567890");
    req.session.vimg = r.random(3);
    pw.createReadStream(req.session.vimg).pipe(res);
})


module.exports = router;
